import axios from "axios";
import {ElMessage, ElMessageBox} from 'element-plus'
import {getToken,removeToken} from "@/utils/token.js"

let request = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL_SUFFIX
});
export default request

request.interceptors.request.use(config => {
    let token = getToken();
    if (token) {
        config.headers.authorization = "Bearer " + token
    }

    return config;
})

request.interceptors.response.use(
    resp => {

        let data = resp.data

        if (data.code === 401) {
            ElMessageBox.confirm(
                '登录状态已过期，您可以继续留在该页面，或者重新登录',
                '系统提示',
                {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    removeToken()
                    location.href = '/login';
                })
                .catch(() => {
                })
            return
        }

        if (data.code !== 200) {
            ElMessage({
                type: "error",
                message: data.msg
            })
        }


        return Promise.resolve(data);

    },
    error => {
        ElMessage({
            type: "error",
            message: "系统异常"
        })
        return Promise.reject(error);

    })

export function postJson(url, data) {
    return request({
        url: url,
        method: "post",
        data: data
    })
}

export function putJson(url, data) {
    return request({
        url: url,
        method: "put",
        data: data
    })
}

export function get(url, params) {
    return request({
        url: url,
        method: "get",
        params: params
    })
}



